<template>
  <div>
    <template>
      <el-card class="box-card" style="height: 70px">
        <el-form :inline="true" :model="searchForm" ref="searchForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input type="text" v-model="searchForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="searchForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button @click="resetForm('searchForm')">重置</el-button>
            <el-button type="success" @click="openAddFormVisible">添加</el-button>
            <el-button type="danger" @click="delBatch">批量删除</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!--      添加用户时弹出的表格-->
      <el-dialog :title="title"  width="33%" :visible.sync="userAddFormVisible" :close-on-click-modal="false">
        <el-form :model="user"  label-width="70px">
          <el-form-item label="用户名" >
            <el-input v-model="user.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="user.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话号">
            <el-input v-model="user.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="注册日期">
            <!--value-format="yyyy-MM-dd" 格式化日期,解决日期少一天的问题-->
            <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="user.createTime"
                            style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="工资">
            <el-input v-model="user.money" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio v-model="user.sex" :label="1">男</el-radio>
            <el-radio v-model="user.sex" :label="2">女</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser ">确 定</el-button>
        </div>
      </el-dialog>

      <el-card class="box-card">
        <el-table
            :data="userList"
            style="width: 100%;"
            @selection-change="handleSelectionChange">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="id"
              label="编号">
          </el-table-column>
          <el-table-column
              prop="username"
              label="姓名">
          </el-table-column>
          <el-table-column
              prop="password"
              label="密码">
          </el-table-column>
          <el-table-column
              prop="phone"
              label="电话号">
          </el-table-column>
          <el-table-column
              prop="createTime"
              label="注册日期">
          </el-table-column>
          <el-table-column
              prop="money"
              label="工资">
          </el-table-column>
          <el-table-column
              prop="sex"
              label="性别">
            <template slot-scope="scope">
              <el-tag
                  :type="scope.row.sex == '1' ? 'primary' : 'success'"
                  disable-transitions>{{ scope.row.sex == '1' ? '男' : '女' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              prop="controls"
              label="操作">
            <template slot-scope="scope">
              <el-button @click="handleEdit(scope.row)" type="text" size="small" >编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
<!--              <el-button-->
<!--                  size="mini"-->
<!--                  @click="handleEdit(scope.row)">编辑-->
<!--              </el-button>-->
<!--              <el-button-->
<!--                  size="mini"-->
<!--                  type="danger"-->
<!--                  @click="handleDelete(scope.row)">删除-->
<!--              </el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <!--
      page-size  每页最大展示条目
      current-page 默认第几页
      total 总条目数
      -->
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="PageNum"
            :page-sizes="[5, 6, 7, 8]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-card>
    </template>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "UserView",
  data() {
    return {
      userList: [],
      ids: [],//删除用到的
      multipleSelection: [],
      userAddFormVisible: false, // 添加对话框,默认不可见
      user: {
        username:'',
        password:'',
        phone:'',
        createTime:'',
        money:0.0,
        sex:1,
      },
      searchForm: {
        username: '',
        password: '',

      },
      pageSize: 5,
      total: 0,
      PageNum: 1,
      dialogFormVisible: false,
      title:"增加用户",
    }
  },
  methods: {
    //查询所有
    findUserList() {
      axios.get('/user/list', {
        params: {
          username: this.searchForm.username,//为了模糊查询
          password: this.searchForm.password,//为了模糊查询
          pageSize: this.pageSize,
          PageNum: this.PageNum,
        }
      }).then((res) => {

        if (res.code === 200) {
          this.userList = res.data.list;
          if (this.userList.length == 0) {
            this.$message({
              message: '没有相关数据！',
              type: 'error',
              // duration: 1000
            });
          }
          this.total = res.data.total
        } else {
          this.$message.error('数据查询失败!');
        }
      })
          .catch((error) => {
            this.$message.error('执行失败！' + error);
          })
    },

    //前端序号
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(val.id)

      let ids = []
      for (let i = 0; i < val.length; i++) {
        ids.push(val[i].id)
      }

      //付给外面的ids
      this.ids = ids;
      // console.log(ids.join(","))

      //   TODO 批量删除
    },

    // 调出增加或者修改框
    openAddFormVisible() {
      // TODO 添加用户
      this.user={};
      this.title="增加用户";
     this.userAddFormVisible =true;

    },
    handleEdit(row){
      // TODO 更新
      // console.log(row)
      this.title="修改用户数据";

      this.user = row
      this.userAddFormVisible =true;

    },
    // 添加用户
    addUser(){
      console.log(this.title)
      if(this.title == "增加用户"){
        axios.post("/user/appendUser",this.user)
            .then((res)=>{
              if(res.code === 2000){
                this.$message.success('添加成功!');
                this.findUserList()
                this.userAddFormVisible =false;
              }else {
                this.$message.error('添加失败!');
              }
            })
            .catch((error)=>{
              this.$message.error('请检查输入的参数格式！'+error);
            })
      }else if(this.title == "修改用户数据"){
        // console.log("准备更新", this.user)   // 这是编辑的用户信息
          axios.post("/user/updateByUser",this.user)
              .then((res)=>{
                console.log( res)
                if(res.code === 2000){
                  this.$message.success('修改成功!');
                  this.findUserList()
                  this.userAddFormVisible =false;
                }else {
                  this.$message.error('修改失败!');
                }
              })
      }else{
        this.$message.error('未知的操作请重新选择！'+error);
      }
    },
    handleDelete(row) {
      // TODO 删除
      // console.log(row.id);
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.get("/user/handleDelete", {
          params: {
            id: row.id
          }
        }).then((res) => {
          if (res.code === 1) {
            //删除成功后，跳转到第一页且，从新查询
            this.$message.success('删除成功！');
            this.PageNum = 1;
            this.findUserList()
          }
        }).catch((error) => {
          this.$message.error('删除执行异常！' + error);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    resetForm(formName) {

      this.$refs[formName].resetFields();
    },
    search() {
      // console.log(this.searchForm);

      // TODO 模糊搜索
      this.findUserList()//调用查询所有


    },
    delBatch() {
      // TODO 批量删除
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.get("/user/delBatch", {
          params: {
            ids: this.ids.join(",")
          }
        }).then((res) => {
          if (res.code === 2000) {
            this.$message.success('删除成功！');
            this.PageNum = 1;
            this.findUserList()
          } else {
            this.$message.error('删除执行异常！');
          }
        }).cache((error) => {
          this.$message.error('删除执行异常！' + error);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.findUserList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.PageNum = val;
      this.findUserList()
    }
  },
  onSubmit() {
    console.log('submit!');
  },
  handleClick() {

  },
  created() {
    this.findUserList()
  }
}
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 100%;
}
</style>